package com.bnq.logc.ui.file

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.bnq.logc.R


class FileBrowserActivity : AppCompatActivity(){

    private var mFragmentManager: FragmentManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_browser)

        setFragmentContentController()
    }

    private fun setFragmentContentController(){
        // 获取FragmentManager
        mFragmentManager = supportFragmentManager

        val fileBrowserFragment = FileBrowserFragment().apply {
            setOnBack { finish() }

            setOnViewFileCallback {
                val fragment = WebViewFragment().apply {
                    arguments = bundleOf("url" to "file://$it")
                    setOnBack {
                        mFragmentManager?.popBackStack()
                    }
                }
                navigate(fragment)
            }
        }

        navigate(fileBrowserFragment)
    }

    private fun navigate(fragment: Fragment, addToBackStack: Boolean = true){
        mFragmentManager?.beginTransaction()?.apply {
            if(mFragmentManager!!.fragments.size > 0){
                hide(mFragmentManager!!.fragments[mFragmentManager!!.fragments.size - 1])
                add(R.id.fragment_container, fragment)
            }else {
                replace(R.id.fragment_container, fragment)
            }
            if(addToBackStack){
                addToBackStack(null)
            }
            commit()
        }
    }
}